package com.yunxiangyue

//import cn.edu.sicnu.lgy.finalwork.info_user.user_info

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.google.android.material.navigation.NavigationView
import com.google.android.material.tabs.TabLayout
import com.makeramen.roundedimageview.RoundedImageView
import com.yunxiangyue.CreateList.MusicDataBase
import com.yunxiangyue.CreateList.MusicListDao
import com.yunxiangyue.CreateList.MusicListItem
import com.yunxiangyue.app.R
import com.yunxiangyue.info_user.mainActivity
import com.yunxiangyue.logger.Logger
import com.yunxiangyue.musicplayer.music_play_list
import de.hdodenhof.circleimageview.CircleImageView
import java.io.ByteArrayOutputStream
import java.io.FileNotFoundException
import java.io.IOException

const val TAG = "mineFragment"

class mine_fragement : Fragment(), View.OnClickListener, ViewPager.OnPageChangeListener {

    var user_name: TextView? = null

    private lateinit var viewCreate:View
    private lateinit var viewCollect:View
    private lateinit var viewAssistance:View
    private lateinit var phone:String
    private lateinit var createImg:ImageView
    private var musicCreateList:MutableList<musicListItem> = ArrayList<musicListItem>()
    private var defalultDowload:String = "已经收入20首歌"
    private lateinit var requestPermissionLauncher:ActivityResultLauncher<String>
    private lateinit var mlauncher:ActivityResultLauncher<Intent?>
    private lateinit var imgDia:RoundedImageView
    private var count:Int= 0
    private lateinit var musicCreateDao: MusicListDao

    private var imgUri:Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                // 权限被授予
                selectImg()
            } else {
                // 权限被拒绝
                Toast.makeText(activity,"你未打开该权限",Toast.LENGTH_SHORT).show()
            }
        }

        mlauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if (it.resultCode == AppCompatActivity.RESULT_OK) {
                    val intent = it?.data
                    imgUri = intent?.data
                    if(imgUri!=null){
                        imgDia.setImageURI(imgUri)
                    }

                }
            })


    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_mine_fragement, container, false)

    }

    lateinit var header:TextView
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //创建歌单列表的 Dao类用于对该用户的歌单信息进行查询插入或删除
        musicCreateDao = MusicDataBase.getMusicDatabase(requireActivity()).MusicListDao()
        user_name = view.findViewById<TextView>(R.id.user_name)
        view.findViewById<CircleImageView>(R.id.userPhoto).setOnClickListener(this)
        view.findViewById<LinearLayout>(R.id.linearFavorite).setOnClickListener(this)
        view.findViewById<ImageView>(R.id.imageView2).setOnClickListener(this)
        view.findViewById<Button>(R.id.button12).setOnClickListener(this)

        val navView = view.findViewById<NavigationView>(R.id.navView)
//        navView.setCheckedItem(R.id.msg)
        header = navView.getHeaderView(0).findViewById<TextView>(R.id.u_name)
        //对侧边栏的各项进行点击相应的事件

        navView.setNavigationItemSelectedListener { MenuItem ->
            Log.d("ning", "点击了菜单项: ${MenuItem.itemId}")
            when(MenuItem.itemId){
                R.id.logOut_ -> {
                    //回退到登录页面
                    Log.d("ning","您已点击退回按钮")
                    requireActivity().finish()

                }
            }
            true
        }


        //tabLayout和viewPager实现滑动翻页效果
        val viewpager = view.findViewById<ViewPager>(R.id.viewpager2)
        var views:MutableList<View> = ArrayList<View>()
        var titles:MutableList<String> = ArrayList<String>()
        viewCreate = LayoutInflater.from(activity).inflate(R.layout.create_list,null)
        viewCollect = LayoutInflater.from(activity).inflate(R.layout.collect_list,null)
        viewAssistance = LayoutInflater.from(activity).inflate(R.layout.assistance_list,null)
        views.add(viewCreate)
        views.add(viewCollect)
        views.add(viewAssistance)
        titles.add("创建歌单")
        titles.add("收藏歌单")
        titles.add("歌单助手")

        //点击新建歌单的图标
        createImg = viewCreate.findViewById<ImageView>(R.id.create_img)
        createImg.setOnClickListener(this)
        val adpter:RegisterAddForgetAdapter = RegisterAddForgetAdapter(views,titles)
        val tablay = view.findViewById<TabLayout>(R.id.tablayout2)
        for (t in titles){
            tablay.addTab(tablay.newTab().setText(t))
        }
        viewpager.adapter = adpter
        tablay.setupWithViewPager(viewpager)
        viewpager.addOnPageChangeListener(this)
//        initPageOne()
        var layoutManager:LinearLayoutManager
        var recyclerView:RecyclerView? = null
        var rvadpter:rvListAdapter

        if(musicCreateList.size == 0){
            layoutManager = LinearLayoutManager(activity)
            recyclerView = viewCreate.findViewById<RecyclerView>(R.id.rv1)
            recyclerView.layoutManager = layoutManager
        }

        rvadpter = rvListAdapter(musicCreateList)
        recyclerView?.adapter = rvadpter


        //设置列表每一项的长按事件，重写接口的长按方法   对列表项达到修改或者删除的目的
        rvadpter.setOnItemLongClickListener(
            object : rvListAdapter.OnItemLongClickListener {
                override fun onItemLongClick(view: View,position: Int): Boolean {
                    //获取点击的一项的视图
                    Log.d("ning","您已长按改时间$position")
                    val menu = PopupMenu(requireContext().applicationContext,view)
                    menu.menuInflater.inflate(R.menu.listitem_menu,menu.menu)
                    menu.setOnMenuItemClickListener {
                        //删除该项   注意每一项的title都是唯一的
                        val title = musicCreateList.get(position)!!.title
                        Log.d("ning","删除的是title:$title")
                        when(it.itemId){
                            R.id.delete_item -> {
                                //删除指定位置的某一项  要使得列表中的元素和列表项元素一一对应   1：每删除一个列表项,后面的列表项的索引依次减一   2：保持List的大小不变，删除元素的位置将其置为null
                                musicCreateList.removeAt(position)
//                                rvadpter.deleteItem(position)
                                rvadpter.notifyItemRemoved(position)
                                rvadpter.notifyItemRangeChanged(position,musicCreateList.size+1)

                                //将bitmap图片转换为字节数组
//                                val stream = ByteArrayOutputStream()
//                                val bitmap:Bitmap = musicCreateList.get(position).imgBit
//                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
//                                val imgByte = stream.toByteArray()
//                                val info =musicCreateList.get(position).dowloadInfo

                                musicCreateDao.deleteMusicList(title)
                                Log.d("ning","列表的长度为:"+musicCreateList.size)
                                Log.d("ning","您已点击删除时间")
                            }

                            R.id.rectify_item -> {
                                //修改该项
                                val list = musicCreateDao.queryAllByTitle(title)
                                Log.d("ning","您已点击修改事件")
                            }
                        }
                        true
                    }
                    menu.show()
                    return true
                }
            }
        )

//        删除表中所有数据
//        musicCreateDao.deleteAll()

        //后面删
        phone = "18284190458"
        //查询该手机用户的所有歌单信息  将该用户的字节类型的图像转换为bitmap类型依次存入musicCreateList列表中
        val createList = musicCreateDao.queryAllByPhone(phone)
        if(createList.size != 0){
            for(li in createList){
                val blob: ByteArray = li.imgResource
                val bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.size)
                musicCreateList.add(musicListItem(bitmap,li.musicTitle,li.info))
            }
        }


    }

    companion object {
        fun newInstance() = mine_fragement()
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.userPhoto -> {
                val intent= Intent(activity, mainActivity::class.java)
                intent.putExtra("phone",phone)
                startActivityForResult(intent,1)
            }
            R.id.linearFavorite -> {
                val intent= Intent(activity, music_play_list::class.java)
                startActivity(intent)
            }
            R.id.imageView2 -> {
                val intent= Intent(activity,music_play_list::class.java)
                startActivity(intent)
            }
            R.id.lay1 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",1)
                startActivity(intent)
            }
            R.id.lay2 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",2)
                startActivity(intent)
            }
            R.id.lay3 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",3)
                startActivity(intent)
            }
            R.id.lay4 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",4)
                startActivity(intent)
            }
            R.id.lay5 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",5)
                startActivity(intent)
            }
            R.id.lay6 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",6)
                startActivity(intent)
            }
            R.id.lay7 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",7)
                startActivity(intent)
            }
            R.id.lay8 -> {
                val intent= Intent(activity,music_play_list::class.java)
                intent.putExtra("num",8)
                startActivity(intent)
            }
            R.id.search -> {
                val intent = Intent()
                intent.action = "android.intent.action.VIEW"
                val content_url: Uri = Uri.parse("https://music.163.com/#/my/m/music/playlist?id=2534456488")
                intent.data = content_url
                startActivity(intent)
            }
            R.id.user_name -> {
                //跳转到修改信息界面
//                val intent=Intent(activity,user_info::class.java)
//                startActivityForResult(intent,1)
            }

            //滑动菜单处
            R.id.button12 -> {
                header.setText(user_name?.text.toString())
                view?.findViewById<DrawerLayout>(R.id.drawerLayoutOut)?.openDrawer(GravityCompat.START)
            }

            R.id.create_img -> {
                //弹出一个对话框填入歌单基本信息
                showDialogInput()
            }

            //点击弹出对话框中的选择封面图片按钮
            R.id.createBtn -> {
                //1选择本地图片作为歌单封面  并把对话框Img设置为本地图片
                if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1);
                } else {
                    //访问相册
                    selectImg()
                }

                Log.d("ning","点击创建按钮")
            }
        }
    }

    //选择本地图片并将其转换为字节数组
    private fun selectImg(){
        val intent=Intent(Intent.ACTION_GET_CONTENT)
        intent.setType("image/*")
        mlauncher.launch(intent)

    }


    //弹出对话框 对歌单进行创建
    private fun showDialogInput(){
        val inflate = layoutInflater
        val dialogView = inflate.inflate(R.layout.dialog_layout,null)
        val inputEdit = dialogView.findViewById<EditText>(R.id.editDia)
        val img = dialogView.findViewById<ImageView>(R.id.imgDia)
        val createBtn = dialogView.findViewById<Button>(R.id.createBtn)
        imgDia = dialogView.findViewById(R.id.imgDia)
        createBtn.setOnClickListener(this)

        val builder =  AlertDialog.Builder(requireActivity())
        builder.setView(dialogView)
            .setPositiveButton("确认创建"){dialog,id ->
                count++
                //获取并处理用户的输入  新建一个item项  将标题名和图片设置到recyclerView的列表项中
                val resolver = context?.contentResolver
                val originUri = imgUri
                try {
                    Logger.debug(TAG, "create")
                    val bitmap = MediaStore.Images.Media.getBitmap(resolver,originUri)
                    val stream = ByteArrayOutputStream()
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                    val imgByte = stream.toByteArray()
//                    musicCreateList.add(musicListItem(bitmap,inputEdit.text.toString(),defalultDowload))
                    rvListAdapter(musicCreateList).addItem(musicListItem(bitmap,inputEdit.text.toString(),defalultDowload))

                    musicCreateDao.insertMusic(MusicListItem(phone,imgByte,inputEdit.text.toString(),defalultDowload))

                }catch (e:FileNotFoundException){
                    e.printStackTrace()
                }catch (e:IOException){
                    e.printStackTrace()
                }
                Log.d("ning","第$count"+"次创建"+"列表长度为${musicCreateList.size}")
                Log.d("ning",inputEdit.text.toString())


            }
            .setNegativeButton("取消"){dialog,id ->
//                        用户点击了取消按钮

            }
        val dialog = builder.create()
        dialog.show()
        dialog.window?.setBackgroundDrawableResource(R.drawable.dialog_bg)


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==1){
            if(resultCode==1){
                val data=data?.getBundleExtra("bun")
                val name=data?.getString("name")
                user_name?.text=name
            }
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

    }

    override fun onPageSelected(position: Int) {
        if(position == 0){
            //选择的是第一个页面   将RecyclerView渲染到该页面
//            initPageOne()
            Log.d("ning","选择的是第一个页面")

            //新建一个歌单
//            createImg.setOnClickListener(this)
        }else if(position == 1){
            //选择的是第二个页面   将RecyclerView渲染到该页面
            val musicList = initCollectList()
            val layoutManager = LinearLayoutManager(activity)
            val recyclerView = viewCollect.findViewById<RecyclerView>(R.id.rv2)
            recyclerView.layoutManager = layoutManager
            val adpter = rvListAdapter(musicList)
            recyclerView.adapter = adpter
        }else if(position == 2){
            //选择的是第三个页面   将RecyclerView渲染到该页面
            val musicList = initAssistance()
            val layoutManager = LinearLayoutManager(activity)
            val recyclerView = viewAssistance.findViewById<RecyclerView>(R.id.rv3)
            recyclerView.layoutManager = layoutManager
            val adpter = rvListAdapter(musicList)
            recyclerView.adapter = adpter
        }

    }

    public fun setParams(params:String){
        phone = params
        Log.d("ning","mine得到的号码是:$phone")
    }

    override fun onPageScrollStateChanged(state: Int) {

    }

    fun initCollectList():MutableList<musicListItem>{
        var musicList:MutableList<musicListItem> = ArrayList()
        val dra:Drawable = R.drawable.background3.toDrawable()
        val bitmap = drawableToBitmap(dra)
        val dra2:Drawable = R.drawable.b2.toDrawable()
        val bitmap2 = drawableToBitmap(dra2)
        musicList.add(musicListItem(bitmap!!,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2!!,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        return musicList
    }


    fun drawableToBitmap(drawable: Drawable): Bitmap {
        val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // 创建一个临时的小Bitmap
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height) // 设置Drawable的边界
        drawable.draw(canvas) // 在临时Bitmap上绘制Drawable以测量其尺寸

        // 测量Drawable的实际尺寸
        val drawableWidth = drawable.bounds.width()
        val drawableHeight = drawable.bounds.height()

        // 创建一个与Drawable实际尺寸相同的Bitmap
        val resultBitmap = Bitmap.createBitmap(drawableWidth, drawableHeight, Bitmap.Config.ARGB_8888)
        val resultCanvas = Canvas(resultBitmap)

        // 在新的Bitmap上重新绘制Drawable
        drawable.setBounds(0, 0, drawableWidth, drawableHeight)
        drawable.draw(resultCanvas)

        return resultBitmap
    }

    fun initAssistance():MutableList<musicListItem>{
        var musicList:MutableList<musicListItem> = ArrayList()
        val dra:Drawable = R.drawable.background3.toDrawable()
        val bitmap = drawableToBitmap(dra)
        val dra2:Drawable = R.drawable.b2.toDrawable()
        val bitmap2 = drawableToBitmap(dra2)
        musicList.add(musicListItem(bitmap!!,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2!!,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap,"我喜欢的音乐","已经下载20首"))
        musicList.add(musicListItem(bitmap2,"我喜欢的音乐","已经下载20首"))
        return musicList
    }
}